<template>
	<div>
		<a-card :title="dbsName" :bordered="false">
			<template #extra>
				<a v-if="dbTableList.length > 0" @click="formRef.onOpen({ dbsId: dbsId })">
					<plus-outlined />
					新增
				</a>
			</template>
			<a-table
				v-if="dbTableList.length > 0"
				:dataSource="dbTableList"
				:columns="columns"
				:scroll="{ y: 600 }"
				:pagination="false"
				bordered
				size="middle"
			>
				<template #bodyCell="{ column, record }">
					<template v-if="column.dataIndex === 'tableName'">
						<a @click="selectTableName(record.tableName)">{{ record.tableName }}</a>
					</template>
					<template v-if="column.dataIndex === 'action'">
						<a @click="formRef.onOpen({ ...record, dbsId: props.dbsId, isEdit: true })"> 修改 </a>
						<a-divider type="vertical" />
						<a-popconfirm title="确定要删除字段吗？" placement="topRight" @confirm="deleteTable(record)">
							<a-button type="link" danger size="small">删除</a-button>
						</a-popconfirm>
					</template>
				</template>
			</a-table>
			<a-empty v-else :image="Empty.PRESENTED_IMAGE_SIMPLE" />
		</a-card>
		<Form ref="formRef" @successful="formSuccessful" />
	</div>
</template>
<script setup>
	import { Empty } from 'ant-design-vue'
	import dmApi from '@/api/dev/dmApi'
	import Form from './form.vue'

	const emits = defineEmits(['selectTableName'])
	const props = defineProps({
		dbsId: {
			type: String,
			request: true,
			default: ''
		},
		dbsType: {
			type: String,
			request: true,
			default: ''
		},
		dbsName: {
			type: String,
			request: true,
			default: ''
		}
	})
	const columns = ref([
		{
			title: '表名',
			dataIndex: 'tableName',
			key: 'tableName',
			align: 'center'
		},
		{
			title: '注释',
			dataIndex: 'tableRemark',
			key: 'tableRemark',
			align: 'center'
		},
		{
			title: '操作',
			dataIndex: 'action',
			width: 120,
			align: 'center'
		}
	])
	// 数据库表
	const formRef = ref()
	const dbTableList = ref([])

	const selectTableName = (value) => {
		emits('selectTableName', value)
	}

	const formSuccessful = () => {
		getDbTableList()
	}

	// 获取数据库表
	const getDbTableList = () => {
		const param = {
			dbsId: props.dbsId
		}
		dmApi.tables(param).then((data) => {
			dbTableList.value = data
		})
	}

	const deleteTable = (item) => {
		const param = {
			dbsId: props.dbsId,
			tableName: item.tableName
		}
		dmApi.deleteTable(param).then((data) => {
			getDbTableList()
		})
	}

	// 抛出函数
	defineExpose({
		getDbTableList
	})
</script>
